using System.Web.Mvc;
using AgileBoard.Core;
using AgileBoard.Infrastructure.Extensions;
using AgileBoard.Infrastructure.StateStorage;
using AgileBoard.Web.Controllers.ViewModel;
using SharpArch.Core;
using SharpArch.Core.PersistenceSupport;
using SharpArch.Web.NHibernate;

namespace AgileBoard.Web.Controllers
{
    [HandleError]
    public class IterationsController : Controller
    {
        private readonly IRepository<Iteration> iterationRepository;
        private readonly IRepository<Project> projectRepository;
        private readonly UserProfile userProfile;

        public IterationsController(
            IRepository<Iteration> iterationRepository, 
            IRepository<Project> projectRepository, 
            UserProfile userProfile)
        {
            Check.Require(iterationRepository != null, "iterationRepository may not be null");

            this.iterationRepository = iterationRepository;
            this.projectRepository = projectRepository;
            this.userProfile = userProfile;
        }

        [Transaction]
        public ActionResult Index()
        {
            if (userProfile.ProjectId == 0)
                return RedirectToAction("index", "projects");

            var project = projectRepository.Get(userProfile.ProjectId);
            var iterationView = IterationIndexView.Create(project.Iterations);

            return View(iterationView);
        }

        [Transaction]
        public ActionResult Show(int id)
        {
            var iteration = iterationRepository.Get(id);
            return View(iteration);
        }

        public ActionResult Create()
        {
            IterationFormViewModel viewModel = IterationFormViewModel.CreateIterationFormViewModel();
            return View(viewModel);
        }

        [ValidateAntiForgeryToken]
        [Transaction]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(Iteration iteration)
        {
            if (ViewData.ModelState.IsValid && iteration.IsValid())
            {
                var project = projectRepository.Get(userProfile.ProjectId);

                iteration.AddStates(project.DefaultStates);
                project.AddIteration(iteration);
                projectRepository.SaveOrUpdate(project);

                TempData[ControllerEnums.GlobalViewDataProperty.PageMessage.ToString()] =
                    "The iteration was successfully created.";
                return RedirectToAction("Index");
            }

            IterationFormViewModel viewModel = IterationFormViewModel.CreateIterationFormViewModel();
            viewModel.Iteration = iteration;
            return View(); ;
        }

        [Transaction]
        public ActionResult Edit(int id)
        {
            IterationFormViewModel viewModel = IterationFormViewModel.CreateIterationFormViewModel();
            viewModel.Iteration = iterationRepository.Get(id);
            return View(viewModel);
        }

        [ValidateAntiForgeryToken]
        [Transaction]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(Iteration iteration)
        {
            Iteration iterationToUpdate = iterationRepository.Get(iteration.Id);
            TransferFormValuesTo(iterationToUpdate, iteration);

            if (ViewData.ModelState.IsValid && iteration.IsValid())
            {
                TempData[ControllerEnums.GlobalViewDataProperty.PageMessage.ToString()] =
                    "The iteration was successfully updated.";
                return RedirectToAction("Index");
            }
            else
            {
                iterationRepository.DbContext.RollbackTransaction();

                IterationFormViewModel viewModel = IterationFormViewModel.CreateIterationFormViewModel();
                viewModel.Iteration = iteration;
                return View(viewModel);
            }
        }

        private void TransferFormValuesTo(Iteration iterationToUpdate, Iteration iterationFromForm)
        {
            iterationToUpdate.Label = iterationFromForm.Label;
            iterationToUpdate.Start = iterationFromForm.Start;
            iterationToUpdate.Finish = iterationFromForm.Finish;
        }

        [ValidateAntiForgeryToken]
        [Transaction]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete(int id)
        {
            string resultMessage = "The iteration was successfully deleted.";
            Iteration iterationToDelete = iterationRepository.Get(id);

            if (iterationToDelete != null)
            {
                iterationRepository.Delete(iterationToDelete);

                try
                {
                    iterationRepository.DbContext.CommitChanges();
                }
                catch
                {
                    resultMessage = "A problem was encountered preventing the iteration from being deleted. " +
                                    "Another item likely depends on this iteration.";
                    iterationRepository.DbContext.RollbackTransaction();
                }
            }
            else
            {
                resultMessage = "The iteration could not be found for deletion. It may already have been deleted.";
            }

            TempData[ControllerEnums.GlobalViewDataProperty.PageMessage.ToString()] = resultMessage;
            return RedirectToAction("Index");
        }

        #region Nested type: IterationFormViewModel

        /// <summary>
        /// Holds data to be passed to the Iteration form for creates and edits
        /// </summary>
        public class IterationFormViewModel
        {
            private IterationFormViewModel()
            {
            }

            public Iteration Iteration { get; internal set; }

            /// <summary>
            /// Creation method for creating the view model. Services may be passed to the creation 
            /// method to instantiate items such as lists for drop down boxes.
            /// </summary>
            public static IterationFormViewModel CreateIterationFormViewModel()
            {
                var viewModel = new IterationFormViewModel();

                return viewModel;
            }
        }

        #endregion

        
    }
}